package com.ly.base.chapter04.framwork;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * JdbcTemplate  (需要导 jdbc 依赖)
 */
public class JdbcTemplateDemo02 {
    public static void main(String[] args) {
        // 1 创建啊数据库连接对象
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("1234");
/*        List<JdbcTemplateDemo01.Student> stuList = new ArrayList<>();
        try (Connection conn = dataSource.getConnection()) { //dataSource.getConnection() --- 建立数据库连接
            PreparedStatement stat = conn.prepareStatement("select * from student");
            ResultSet rs = stat.executeQuery();
            while (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String sex = rs.getString("sex");
                stuList.add(new JdbcTemplateDemo01.Student(id,name,sex));
            }
            for (JdbcTemplateDemo01.Student stu : stuList) {
                System.out.println(stu);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }*/
        // 2 创建JdbcTemplate对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        List<Student> studentList = jdbcTemplate.query("select * from student", (rs, row) -> {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String sex = rs.getString("sex");
            return new Student(id, name, sex);
        });
        for (Student student : studentList) {
            System.out.println(student);
        }

    }


    record Student(int id, String name, String sex) { }
}
